<?php namespace Phpcmf\Controllers\Admin;

class Config extends \Phpcmf\App
{

    public function index() {

        $data = \Phpcmf\Service::M('app')->get_config(APP_DIR);

        if (IS_AJAX_POST) {

            $post = \Phpcmf\Service::L('input')->post('data');
            \Phpcmf\Service::M('app')->save_config(APP_DIR, $post);

            $this->_json(1, dr_lang('操作成功'));
        }

        $page = intval(\Phpcmf\Service::L('input')->get('page'));

        \Phpcmf\Service::V()->assign([
            'page' => $page,
            'data' => $data,
            'form' => dr_form_hidden(['page' => $page]),
            'menu' => \Phpcmf\Service::M('auth')->_admin_menu(
                [
                    '百度翻译多语言' => [APP_DIR.'/'.\Phpcmf\Service::L('Router')->class.'/index', 'fa fa-cog'],
                    'help' => [1062],
                ]
            ),
            'module' => \Phpcmf\Service::L('cache')->get('module-'.SITE_ID.'-content')
        ]);
        \Phpcmf\Service::V()->display('config.html');

    }

    public function test_index() {

        if (function_exists('my_translate_lang')) {
            $this->_json(1, '代码已经生效');
        } else {
            $this->_json(0, '以上代码没有放入正确');
        }

    }

    public function lang_index() {

        if (IS_POST) {
            $post = \Phpcmf\Service::L('input')->post('post');
            $rt = \Phpcmf\Service::L('lang', 'usu_fanyi')->translate($post['text'], 'auto', $post['lang']);
            if ($rt) {
                $this->_json(1, $rt);
            }
            $this->_json(0, '翻译失败：'.\Phpcmf\Service::L('lang', 'usu_fanyi')->error);
        } else {
            $this->_json(0, '请求异常');
        }

    }

    public function error_index() {

        $img = dr_get_app_dir(APP_DIR).'Config/error.jpg';
        $info = getimagesize($img);
        $imgExt = image_type_to_extension($info[2], false);  //获取文件后缀
        $fun = "imagecreatefrom{$imgExt}";
        $imgInfo = $fun($img); 					//1.由文件或 URL 创建一个新图象。如:imagecreatefrompng ( string $filename )
        //$mime = $info['mime'];
        $mime = image_type_to_mime_type($info[2]); //获取图片的 MIME 类型
        header('Content-Type:'.$mime);
        $quality = 100;
        if($imgExt == 'png') $quality = 9;		//输出质量,JPEG格式(0-100),PNG格式(0-9)
        $getImgInfo = "image{$imgExt}";
        $getImgInfo($imgInfo, null, $quality);	//2.将图像输出到浏览器或文件。如: imagepng ( resource $image )
        imagedestroy($imgInfo);

    }

    // 同步模块
    public function edit() {

        $mid = dr_safe_filename($_GET['mid']);
        $row = \Phpcmf\Service::M('Module')->table('module')->where('dirname', $mid)->getRow();
        if (!$row) {
            $this->_json(0, dr_lang('此模块[%s]未安装', $mid));
        }

        $ids = [\Phpcmf\Service::L('input')->get('cid')];
        if (!$ids) {
            $this->_json(0, dr_lang('所选内容不存在'));
        }

        $site = dr_string2array($row['site']);

        // 计算可用站点信息
        $list = [];
        foreach ($this->site_info as $siteid => $t) {
            $module = \Phpcmf\Service::L('cache')->get('module-'.$siteid.'-'.$mid);
            if (isset($site[$siteid]) && $module && $siteid != SITE_ID) {
                $list[$siteid] = [
                    'name' => $t['SITE_NAME'],
                    'lang' => $t['SITE_LANGUAGE'] ? $t['SITE_LANGUAGE'] : '未设置语言',
                    'select' => \Phpcmf\Service::L('category', 'module')->select(
                        $module['mid'],
                        0,
                        'name="data['.$siteid.'][catid]"',
                        '-不同步-',
                        1, 1
                    ),
                ];
            }
        }

        if (IS_POST) {

            $ct = 0;
            $post = \Phpcmf\Service::L('input')->post('data');
            foreach ($ids as $id) {
                $this->_module_init($mid, SITE_ID);
                $data = $this->content_model->get_data($id);
                foreach ($list as $siteid => $t) {
                    if ($list[$siteid]['lang'] == SITE_LANGUAGE) {
                        $this->_json(0, '当前站点的语言与同步站的语言相同，不能翻译');
                    }
                    if ($post[$siteid]['catid']) {
                        // 初始化站点模块
                        $this->_module_init($mid, $siteid);

                        $fields = [];
                        // 主表字段
                        $fields[1] = $this->get_cache('table-'.$siteid, $this->content_model->dbprefix($siteid.'_'.$mid));
                        $cache = $this->get_cache('table-'.$siteid, $this->content_model->dbprefix($siteid.'_'.$mid.'_category_data'));
                        $cache && $fields[1] = array_merge($fields[1], $cache);

                        // 附表字段
                        $fields[0] = $this->get_cache('table-'.$siteid, $this->content_model->dbprefix($siteid.'_'.$mid.'_data_0'));
                        $cache = $this->get_cache('table-'.$siteid, $this->content_model->dbprefix($siteid.'_'.$mid.'_category_data_0'));
                        $cache && $fields[0] = array_merge($fields[0], $cache);

                        // 去重复
                        $fields[0] = array_unique($fields[0]);
                        $fields[1] = array_unique($fields[1]);

                        $save = [];

                        // 主表附表归类
                        foreach ($fields as $ismain => $field) {
                            foreach ($field as $name) {
                                if (isset($data[$name])) {
                                    $value = $data[$name];
                                    if (!is_numeric($value)) {
                                        // 说明是普通储存
                                        if (preg_match_all('/[\x{4e00}-\x{9fff}]+/u', (string)$value, $mt)) {
                                            // 说明包含中文
                                            foreach ($mt[0] as $tt) {
                                                $text = \Phpcmf\Service::L('lang', 'usu_fanyi')->zhiyi($tt, $list[$siteid]['lang']);
                                                if ($text) {
                                                    $value = str_replace($tt, $text, $value);
                                                }
                                            }
                                        }
                                    }
                                    $save[$ismain][$name] = $value;
                                }
                            }
                        }

                        $save[1]['uid'] = $save[0]['uid'] = $data['uid'];
                        $save[1]['catid'] = $save[0]['catid'] = $post[$siteid]['catid'];

                        $save[1]['url'] = '';
                        $save[1]['status'] = 9; //9表示正常发布，1表示审核里面
                        $save[1]['hits'] = 0;
                        $save[1]['displayorder'] = 0;
                        $save[1]['link_id'] = 0;
                        $save[1]['inputtime'] = $save[1]['updatetime'] = SYS_TIME;
                        $save[1]['inputip'] = '127.0.0.1';

                        if (!$this->content_model->table($siteid.'_'.$mid)->where('title', $save[1]['title'])->counts()) {
                            $rt = $this->content_model->save_content(0, $save);
                            if ($rt['code']) {
                                $ct++;
                            }
                        }

                    }
                }
            }
            $this->_json(1, dr_lang('本次同步%s条数据', $ct));
            exit;
        }

        \Phpcmf\Service::V()->assign([
            'ids' => $ids,
            'list' => $list,
            'form' => dr_form_hidden(),
        ]);
        \Phpcmf\Service::V()->display('sync.html');exit;
    }

}
